package com.example;

import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.CompilationUnit;
import org.mybatis.generator.api.dom.java.Field;
import org.mybatis.generator.api.dom.java.InnerClass;
import org.mybatis.generator.internal.DefaultCommentGenerator;
import org.mybatis.generator.internal.util.StringUtility;

import java.util.Properties;

public class CommentGenerator extends DefaultCommentGenerator {
    private boolean addRemarkComments = false;

    /**
     * 设置用户配置的参数
     */
    @Override
    public void addConfigurationProperties(Properties properties) {
        super.addConfigurationProperties(properties);
        this.addRemarkComments = StringUtility.isTrue(properties.getProperty("addRemarkComments"));
    }

    /**
     * 给字段添加注释
     */
    @Override
    public void addFieldComment(Field field, IntrospectedTable introspectedTable,
                                IntrospectedColumn introspectedColumn) {
        String remarks = introspectedColumn.getRemarks();
        //根据参数和备注信息判断是否添加备注信息
        if(addRemarkComments&&StringUtility.stringHasValue(remarks)){
            //数据库中特殊字符需要转义
            if(remarks.contains("\"")){
                remarks = remarks.replace("\"","'");
            }
            addFieldJavaDoc(field, remarks);
        }
    }

    /**
     * 给model的字段添加注释
     */
    private void addFieldJavaDoc(Field field, String remarks) {
        field.addJavaDocLine("/**");
        field.addJavaDocLine(" * " + remarks);
        field.addJavaDocLine(" */");
    }

    @Override
    public void addJavaFileComment(CompilationUnit compilationUnit) {
        // 版权信息
//        compilationUnit.addFileCommentLine("/*");
//        compilationUnit.addFileCommentLine(" * Copyright © SSY All Rights Reserved.");
//        compilationUnit.addFileCommentLine(" */");

        if (compilationUnit instanceof InnerClass) {
            InnerClass tInterface = (InnerClass) compilationUnit;
            tInterface.addJavaDocLine("/**");
            // 这里写死了注释内容，主要是没法获取到表的注释，如商品信息表
            tInterface.addJavaDocLine(" * 表名");
            tInterface.addJavaDocLine(" *");
            tInterface.addJavaDocLine(" * @author Songguoqing");
            tInterface.addJavaDocLine(" * @date " + getDateString());
            tInterface.addJavaDocLine(" */");
//            tInterface.addJavaDocLine("@Entity");

        }
    }
}
